﻿using AutoMapper;
using MediatR;
using Traceability.App.Api.Application.Command.Detail.Cultivation;
using Traceability.App.ErrorCount;
using Traceability.App.InfrasIntructure;
using Traceability.App.Model.Cultivation;

namespace Traceability.App.Api.Application.Handler.Detail.Cultivation
{
    public class UpdateImmunityHandler : IRequestHandler<UpdateImmunityCommand, ApiResult<int>>
    {
        IBaseRepository<ImmunityModel> immRepo;
        IMapper mapper;


        public UpdateImmunityHandler(IBaseRepository<ImmunityModel> immRepo, IMapper mapper)
        {
            this.immRepo = immRepo;
            this.mapper = mapper;
        }
        public  Task<ApiResult<int>> Handle(UpdateImmunityCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
           
            var imm = immRepo.GetAll().Where(x => !x.IsDeleted && x.Id == request.Id).FirstOrDefault();
            if (imm == null)
            {
                res.Msg = "找不到编号";
                res.Code = ApiEnum.Fail;
                return Task.FromResult(res);
            }

            imm = mapper.Map(request, imm);
            
            int a = immRepo.Update(imm).Result;
            if (a > 0)
            {
                res.Msg = "修改免疫信息成功";
                res.Code = ApiEnum.Success;
                res.Datas = a;

            }
            else
            {
                res.Msg = "修改免疫信息失败";
                res.Code = ApiEnum.Fail;
                res.Datas = a;
            }
            return Task.FromResult(res);
        }
    }
}
